package com.sinoglobal.dumping.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.sinoglobal.dumping.R;
import com.sinoglobal.dumping.api.Dumpling_RemoteImpl;
import com.sinoglobal.dumping.base.Dumpling_SinoAsyncTask;
import com.sinoglobal.dumping.base.Dumpling_SinoBaseActivity;
import com.sinoglobal.dumping.base.Dumpling_SinoConstans;
import com.sinoglobal.dumping.bean.Dumpling_DumpingMakeOrderVo;
import com.sinoglobal.dumping.bean.Dumpling_DumplingPaySuccessVo;
import com.sinoglobal.dumping.bean.Dumpling_DumplingPayVo;
import com.sinoglobal.dumping.net.LogIn_ConnectionUtil;
import com.sinoglobal.wallet.activity.W_OrderPayActivity;
import com.sinoglobal.wallet.activity.W_PayPasswordActivity;
import com.sinoglobal.wallet.api.RemoteImpl;
import com.sinoglobal.wallet.app.SinoConstans;
import com.sinoglobal.wallet.entity.W_DynamicKeyEntity;
import com.sinoglobal.wallet.entity.W_HomeBalanceEntity;
import com.sinoglobal.wallet.entity.W_RsVo;
import com.sinoglobal.wallet.entity.W_VerifyPassNumVo;
import com.sinoglobal.wallet.task.MyAsyncTask;
import com.sinoglobal.wallet.util.LogUtils;
import com.sinoglobal.wallet.util.PayResult;
import com.tencent.mm.sdk.constants.Build;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umpay.quickpay.UmpPayInfoBean;
import com.umpay.quickpay.UmpayQuickPay;

import java.math.RoundingMode;
import java.text.DecimalFormat;


/**
 * Created by Administrator on 2015/12/15.
 * 包饺子Activity
 */
public class Dumpling_MakeDumplingActivity extends Dumpling_SinoBaseActivity {
    private EditText dumpling_make_geNum_EditText, dumpling_make_yuanSum_EditText,//饺子个数， 总金额
            dumpling_make_messageNum_EditText;//留言
    private TextView dumpling_make_yuanSum_TV, dumpling_make_payButton;//金额， 去支付按钮

    public View view1;
    private RelativeLayout pay_fu_bao_layout, pay_weChat_layout,cash_card_layout,//支付宝 微信 U付
            pay_wallet_moeny_layout,goods_gopay_layout;//余额  支付按钮
    private ImageView pay_fu_bao_img,pay_weChat_img,cash_card_img,pay_wallet_money_img;

    private int payStyle=0;//支付方式标识
    private PopupWindow mpopupWindow;
    private LinearLayout ll_popup;

    private int cardType;
    private TextView goods_banlance_notice_txt,goods_balance_money_txt;// 余额状态  余额
    private String blanceTxt="0.0";
    private String isHaspass;
    private int errCount=0;
    private String paySuccessId;//支付成功后获取的id

    private String orderId;//用户包饺子生成小锅钱包订单（去支付时调用）接口返回的订单号
    private Dumpling_DumplingPayVo.DumplingPayListVo payVo;//获取的支付订单对象

    private String isRecharge="-1";//1,充值成功。0，充值失败。2待充值,3.提交成功
    private static final int SDK_PAY_FLAG = 1; //支付宝支付用的判断标记
    private MyHandler myHandler;//支付宝支付信息回调 使用静态内部类是防止内存泄露

    /** 请求返回码 **/
    public static final int REQUESTCODE = 1;
    /** 优付支付成功 **/
    private static final String UMPAY_SUCCESS = "0000";
    /** 优付支付取消 **/
    private static final String UMPAY_CANCEL = "1001";

    private IWXAPI api;
//    private WXPayEntryActivity.WechatReciver weChatReciver;
private DumplingPayReciver dumplingPayReciver;//接收钱包w_orderpayactivity中验证密码成功后发送的广播
    //解决总金额第一位输入0后只能输入.
    private InputFilter inputFilter = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            String editContent = dumpling_make_yuanSum_EditText.getText().toString();
            if(editContent!=null && editContent.length()==1){
                if(editContent.equals("0")){
                    if(source.equals(".")){
                        return source;
                    }else{
                        return "";
                    }
                }
            }
            return source;
        }
    };
    /** 限制字符30*/
    private InputFilter inputFilter2 = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            int keep = 30 - (dest.length() - (dend - dstart));
            if (keep <= 0) {
                showToast("字数不能超过30个哦");
                return "";
            } else if (keep >= end - start) {
                return null;
            } else {
                keep += start;
                if (Character.isHighSurrogate(source.charAt(keep - 1))) {
                    --keep;
                    if (keep == start) {
                        showToast("字数不能超过30个哦");
                        return "";
                    }
                }
                return source.subSequence(start, keep);
            }
        }
    };

    @Override
    public void onAntiViolence(View v) {
        if(v.getId()==R.id.dumpling_make_payButton){//去支付按钮
            if(dumpling_make_geNum_EditText.getText().toString().equals("")){
                showToast("饺子个数不能为空");
            }else if(dumpling_make_yuanSum_EditText.getText().toString().equals("")){
                showToast("总金额不能为空");
            }else if(Integer.parseInt(dumpling_make_geNum_EditText.getText().toString()) > 100){
//                showToast("一次最多可发100个饺子");
            }else if(Integer.parseInt(dumpling_make_geNum_EditText.getText().toString()) <= 0){
                showToast("一次最少要发1个饺子");
            }else if (Double.parseDouble(dumpling_make_yuanSum_EditText.getText().toString()) < 0.01){
//                showToast("单个饺子金额不得低于0.01元");
            }else if (Double.parseDouble(dumpling_make_yuanSum_EditText.getText().toString()) > 5000){
//                showToast("单次支付总额不可超过5000元");
            }else if(Double.parseDouble(dumpling_make_yuanSum_EditText.getText().toString())/
                    Double.parseDouble(dumpling_make_geNum_EditText.getText().toString()) < 0.01){
                showToast("单个饺子金额不得低于0.01元");
            }else if(Double.parseDouble(dumpling_make_yuanSum_EditText.getText().toString())/
                    Double.parseDouble(dumpling_make_geNum_EditText.getText().toString()) >200){
                showToast("单个饺子金额不可超过200元");
            }else{

                dumpingMakeOrderNet();//获得订单号

                ll_popup.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.w_push_bottom_in));
                if (mpopupWindow == null) {
                    mpopupWindow = new PopupWindow(this);
                    mpopupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
                    mpopupWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
                    mpopupWindow.setBackgroundDrawable(new BitmapDrawable());
                    mpopupWindow.setFocusable(true);
                    mpopupWindow.setOutsideTouchable(true);
                }
                mpopupWindow.setContentView(view1);
                mpopupWindow.showAtLocation(dumpling_make_payButton, Gravity.BOTTOM, 0, 0);
                mpopupWindow.update();
            }
        }else if(v.getId()==R.id.goods_pay_wallet_moeny_layout){//余额支付
            if(errCount>=5){
//                showDialog(Dumpling_MakeDumplingActivity.this, "提示", "您今日密码输入次数超限，密码被锁定，请于2小时候后再尝试", "返回", R.color.w_c7, "", R.color.w_c14, false,
//                        new DialogOnClickListener() {
//
//                            @Override
//                            public void onSure(View v) {
//                            }
//
//                            @Override
//                            public void onCancle(View v) {
//                            }
//                        });
                return;
            }
            if(Double.valueOf(dumpling_make_yuanSum_EditText.getText().toString())>Double.valueOf(blanceTxt)){
                Toast.makeText(this, "余额不足,请选择其他支付方式", Toast.LENGTH_SHORT).show();
                return;
            }
            payStyle=1;
            goods_banlance_notice_txt.setVisibility(View.GONE);
            pay_wallet_money_img.setVisibility(View.VISIBLE);
            pay_weChat_img.setVisibility(View.GONE);
            pay_fu_bao_img.setVisibility(View.GONE);
            cash_card_img.setVisibility(View.GONE);
        }else if(v.getId()==R.id.goods_pay_fu_bao_layout){//支付宝支付
            pay_fu_bao_img.setVisibility(View.VISIBLE);
            pay_weChat_img.setVisibility(View.GONE);
            cash_card_img.setVisibility(View.GONE);
            pay_wallet_money_img.setVisibility(View.GONE);
            payStyle=2;
        }else if(v.getId()==R.id.goods_pay_weChat_layout){//微信支付
            pay_fu_bao_img.setVisibility(View.GONE);
            pay_weChat_img.setVisibility(View.VISIBLE);
            cash_card_img.setVisibility(View.GONE);
            pay_wallet_money_img.setVisibility(View.GONE);
            payStyle=4;
        }else if(v.getId()==R.id.goods_cash_card_layout){//u付
            pay_fu_bao_img.setVisibility(View.GONE);
            pay_weChat_img.setVisibility(View.GONE);
            pay_wallet_money_img.setVisibility(View.GONE);
            cash_card_img.setVisibility(View.VISIBLE);
            payStyle=3;
            cardType = 1;
        } else if(v.getId()==R.id.goods_gopay_layout){//点击支付按钮
            if(payStyle == 1){
                getSelectPass();
//                Toast.makeText(this, "余额支付", Toast.LENGTH_SHORT).show();
            }else if (payStyle == 4){
                boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;

                if(LogIn_ConnectionUtil.checkApkExist(this, "com.tencent.mm")){
                    if(isPaySupported){
                        getDynamicKey("");//加密
                    }else{
                        showToast("当前微信版本不支持支付！");
                    }
                }else{
                    showToast("请先安装微信！");
                }
            }else{
                getDynamicKey("");
            }
            popuDismiss();
        }
    }

    private class MyHandler extends Handler {


        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);

                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultInfo = payResult.getResult();
                    //支付状态
                    String resultStatus = payResult.getResultStatus();
                    //	Toast.makeText(W_RechargelActivity.this, "支付宝返回码=="+resultStatus, 0).show();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // notifyServer();通知故服务器支付成功
                        // showToast(getString(R.string.pay_success));
                        isRecharge="1";
                        dumpingPaySuccessNet();
                        break;
                    }
                    // 判断resultStatus 为非“9000”则代表可能支付失败
                    // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                    else if (TextUtils.equals(resultStatus, "8000")) {
                        // showToast(getString(R.string.pay_confirming));
                        isRecharge="3";
                        showToast("提交成功");
                    } else if (TextUtils.equals(resultStatus, "6001")) {
                        //   showToast(getString(R.string.pay_confirming));
                        isRecharge="2";
                        showToast("待支付");
                    } else if (TextUtils.equals(resultStatus, "6002")) {
                        showToast("网络连接出错");
                    }else {
                        // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                        //  showToast(getString(R.string.pay_fail));
                        isRecharge="0";
                        showToast("支付失败");
                    }
                    break;
                }
            }
        }
    }
    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.dumpling_make_dumpling_activity);
        mTemplateRightImg.setVisibility(View.GONE);
        mTemplateRightText.setVisibility(View.GONE);
        mTemplateLayout.setBackgroundColor(getResources().getColor(R.color.dumpling_red2));
        findViewById(R.id.title_right_btn_share).setVisibility(View.GONE);
        mTemplateTitleText.setText("包饺子");

        api = WXAPIFactory.createWXAPI(this, null);
        // 将该app注册到微信
        api.registerApp(Dumpling_SinoConstans.DUMPLING_WeCHATID);

        init();
        initpopView();
        getData();
        getUnPassWordNum();
        initReciver();
    }
    /**
     * 注册改变当前体现页面改变isHaspass值的广播
     */
    private void initReciver() {
        // TODO Auto-generated method stub
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.sinoglobal.dumpling.receiver.passwordNum");
        dumplingPayReciver = new DumplingPayReciver();
        registerReceiver(dumplingPayReciver, intentFilter);
    }
    private void init(){
        myHandler=new MyHandler();
        dumpling_make_geNum_EditText = (EditText) findViewById(R.id.dumpling_make_geNum_EditText);
        dumpling_make_yuanSum_EditText = (EditText) findViewById(R.id.dumpling_make_yuanSum_EditText);
        dumpling_make_yuanSum_EditText.setFilters(new InputFilter[]{inputFilter,new InputFilter.LengthFilter(9)});
        dumpling_make_messageNum_EditText = (EditText) findViewById(R.id.dumpling_make_messageNum_EditText);
        dumpling_make_messageNum_EditText.setFilters(new InputFilter[]{inputFilter2});
        dumpling_make_yuanSum_TV = (TextView) findViewById(R.id.dumpling_make_yuanSum_TV);
        dumpling_make_payButton = (TextView) findViewById(R.id.dumpling_make_payButton);
        dumpling_make_payButton.setOnClickListener(this);

        dumpling_make_geNum_EditText.addTextChangedListener(new TextWatcher() {//饺子个数点击事件
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!s.toString().equals("")) {
                    if (Integer.parseInt(dumpling_make_geNum_EditText.getText().toString()) > 100) {
                        showToast("一次最多可发100个饺子");
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                String str = s.toString().trim();

                if (str.indexOf('0') == 0) {//EditText首位不能为0
                    dumpling_make_geNum_EditText.setText("");
                }
            }
        });


        dumpling_make_yuanSum_EditText.addTextChangedListener(new TextWatcher() {//总金额的点击事件
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().equals("")) {
                    dumpling_make_yuanSum_TV.setText("￥0.00");
                } else {
                    if (s.toString().equals(".")) {
                        dumpling_make_yuanSum_EditText.setText("");
                    } else {
                        DecimalFormat df = new DecimalFormat("0.00");
                        df.setRoundingMode(RoundingMode.HALF_UP);
                        dumpling_make_yuanSum_TV.setText("￥" + df.format(Double.valueOf(s.toString())));
                        double price = Double.parseDouble(dumpling_make_yuanSum_EditText.getText().toString());
                        if (price < 0.01 && price != 0) {
                            showToast("单个饺子金额不得低于0.01元");
                        } else if (price > 5000) {
                            showToast("单次支付总额不可超过5000元");
                        }
                    }
                }

            }

            @Override
            public void afterTextChanged(Editable s) {
                String str = s.toString().trim();
                if (errCount >= 5) {
                    goods_banlance_notice_txt.setVisibility(View.VISIBLE);
                    goods_banlance_notice_txt.setText("锁定");
                    goods_balance_money_txt.setText("账户余额(剩余" + blanceTxt + "元)");
                    pay_fu_bao_img.setVisibility(View.VISIBLE);
                    pay_weChat_img.setVisibility(View.GONE);
                    cash_card_img.setVisibility(View.GONE);
                    pay_wallet_money_img.setVisibility(View.GONE);//余额不足默认选择支付宝
                    payStyle = 2;
                    return;
                } else if (!str.equals("") && !dumpling_make_yuanSum_EditText.getText().toString().equals("")) {
                    if (Double.valueOf(dumpling_make_yuanSum_EditText.getText().toString()) > Double.valueOf(blanceTxt != null ? blanceTxt : "0")) {
                        goods_banlance_notice_txt.setVisibility(View.VISIBLE);
                        goods_banlance_notice_txt.setText("不足");
                        goods_balance_money_txt.setTextColor(getResources().getColor((R.color.w_payPass_gray)));
                        goods_balance_money_txt.setText("账户余额(剩余" + blanceTxt + "元)");
                        pay_fu_bao_img.setVisibility(View.VISIBLE);
                        pay_weChat_img.setVisibility(View.GONE);
                        cash_card_img.setVisibility(View.GONE);
                        pay_wallet_money_img.setVisibility(View.GONE);//余额不足默认选择支付宝
                        payStyle = 2;
                    } else {
                        goods_balance_money_txt.setText("账户余额(剩余" + blanceTxt + "元)");
                        goods_balance_money_txt.setTextColor(Color.BLACK);
                        goods_banlance_notice_txt.setVisibility(View.GONE);
                        pay_wallet_money_img.setVisibility(View.VISIBLE);
                        pay_weChat_img.setVisibility(View.GONE);
                        pay_fu_bao_img.setVisibility(View.GONE);
                        cash_card_img.setVisibility(View.GONE);//余额充足默认选择余额
                        payStyle = 1;
                    }
                }

            }
        });

    }

    public void initpopView() {
        // popwindow相关控件的初始化

        view1 = View.inflate(this, R.layout.wallet_goods_pay_popu_list_layout, null);
        ll_popup = (LinearLayout) view1.findViewById(R.id.goods_pay_popu_layout);
        pay_wallet_moeny_layout = (RelativeLayout) view1.findViewById(R.id.goods_pay_wallet_moeny_layout);
        pay_fu_bao_layout = (RelativeLayout) view1.findViewById(R.id.goods_pay_fu_bao_layout);
        pay_weChat_layout = (RelativeLayout) view1.findViewById(R.id.goods_pay_weChat_layout);
        cash_card_layout = (RelativeLayout) view1.findViewById(R.id.goods_cash_card_layout);
        goods_gopay_layout = (RelativeLayout) view1.findViewById(R.id.goods_gopay_layout);
        pay_fu_bao_img = (ImageView) view1.findViewById(R.id.goods_pay_fu_bao_img);
        pay_weChat_img = (ImageView) view1.findViewById(R.id.goods_pay_weChat_img);
        cash_card_img = (ImageView) view1.findViewById(R.id.goods_cash_card_img);
        pay_wallet_money_img = (ImageView) view1.findViewById(R.id.goods_pay_money_img);
        goods_banlance_notice_txt = (TextView) view1.findViewById(R.id.goods_banlance_notice_txt);
        goods_balance_money_txt = (TextView) view1.findViewById(R.id.goods_balance_money_txt);
        pay_fu_bao_layout.setOnClickListener(this);
        pay_weChat_layout.setOnClickListener(this);
        cash_card_layout.setOnClickListener(this);
        pay_wallet_moeny_layout.setOnClickListener(this);
        goods_gopay_layout.setOnClickListener(this);
        view1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                mpopupWindow.dismiss();
            }
        });

    }

    private void popuDismiss() {
        // 向下移动的动画效果
        Animation Animation = AnimationUtils.loadAnimation(this, R.anim.w_push_bottom_out);
        ll_popup.startAnimation(Animation);
        Animation.setAnimationListener(new android.view.animation.Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                LogUtils.v("dismiss--------------");
                mpopupWindow.dismiss();
            }
        });
    }

    // 获取密码错误次数
    private void getUnPassWordNum() {
        MyAsyncTask<W_VerifyPassNumVo> task = new MyAsyncTask<W_VerifyPassNumVo>(true, this, true) {

            @Override
            public W_VerifyPassNumVo before(Void... params) throws Exception {
                // TODO 测试接口
                return RemoteImpl.getInstance().getUnPassWordNum(Dumpling_MakeDumplingActivity.this);
            }

            @Override
            public void after(W_VerifyPassNumVo result) {
                if(result != null){
                    if (result.getCode().equals("100")) {
                        errCount = result.getErrCount();
                        if(errCount<5){
                        }else{
                            goods_banlance_notice_txt.setVisibility(View.VISIBLE);
                            goods_banlance_notice_txt.setText("锁定");
                            goods_balance_money_txt.setText("账户余额(剩余"+blanceTxt +"元)");
                            pay_fu_bao_img.setVisibility(View.VISIBLE);
                            pay_weChat_img.setVisibility(View.GONE);
                            cash_card_img.setVisibility(View.GONE);
                            pay_wallet_money_img.setVisibility(View.GONE);//余额不足默认选择支付宝
                            payStyle = 2;
                        }
                    } else {
                        showToast(result.getDescription());
                    }
                }
            }

            @Override
            public void exception() {
            }
        };
        task.execute();
    }

    private void getData() {
        MyAsyncTask<W_HomeBalanceEntity> task = new MyAsyncTask<W_HomeBalanceEntity>(true,this,true) {


            @Override
            public W_HomeBalanceEntity before(Void... params) throws Exception {
                // TODO 测试接口
                return RemoteImpl.getInstance().getBalance(Dumpling_MakeDumplingActivity.this);
            }

            @Override
            public void after(W_HomeBalanceEntity result) {
                if (result != null) {
                    if (result.getCode().equals("100")) {
                        W_HomeBalanceEntity.RsEntity rs=result.getRs();
                        blanceTxt = rs.getBalance();
                        goods_balance_money_txt.setText("账户余额(剩余"+blanceTxt +"元)");
                        isHaspass = rs.getIsHasPass();
                    }else{
                        Toast.makeText(Dumpling_MakeDumplingActivity.this, "数据加载失败", Toast.LENGTH_SHORT).show();
                    }
                }

            }

            @Override
            public void exception() {
            }
        };
        task.execute();
    }


    //是否设置了支付密码
    private void getSelectPass(){

        MyAsyncTask<W_RsVo> task = new MyAsyncTask<W_RsVo>(true,this,true) {
            @Override
            public W_RsVo before(Void... params) throws Exception {
                // TODO 测试接口
                return RemoteImpl.getInstance().getSelectPassWord(Dumpling_MakeDumplingActivity.this);
            }

            @Override
            public void after(W_RsVo result) {
                if (result != null) {
                    if (result.getCode().equals("100") && result.getRs().equals("N")) {
                        showDialog(Dumpling_MakeDumplingActivity.this, "提示", "您还没有设置支付密码，为了保障您的财产安全，请设置支付密码",
                                "去设置", R.color.w_c14, "等一下", R.color.w_c14,true,new DialogOnClickListener() {
                                    @Override
                                    public void onSure(View v) {
                                        Bundle setting_bundle = new Bundle();
                                        setting_bundle.putString("title_flag", "3");
                                        goIntent(W_PayPasswordActivity.class, setting_bundle);//设置密码
                                    }
                                    @Override
                                    public void onCancle(View v) {
//									showToast("取消");
                                    }
                                });
                    }else if(result.getCode().equals("100") && result.getRs().equals("Y")){
                        Intent intent = new Intent(Dumpling_MakeDumplingActivity.this,W_OrderPayActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("Money", dumpling_make_yuanSum_EditText.getText().toString());
                        bundle.putString("Type", "GOOD");//提现页面传来的标示
                        intent.putExtras(bundle);
                        startActivityForResult(intent,300);
                    }else{
                        showToast(result.getMsg());
                    }
                }
            }

            @Override
            public void exception() {
            }
        };
        task.execute();

    }

    // 获取动态秘钥
    private void getDynamicKey( final String password) {
        MyAsyncTask<W_DynamicKeyEntity> task = new MyAsyncTask<W_DynamicKeyEntity>(true, this, true) {
            @Override
            public W_DynamicKeyEntity before(Void... params) throws Exception {
                // TODO 测试接口
                return RemoteImpl.getInstance().getDynamicKey();
            }
            @Override
            public void after(W_DynamicKeyEntity result) {
                if(result != null){
                    String id="";//
                    String encryptKey="";//动态秘钥
                    id = result.getId();
                    encryptKey = result.getEncryptKey();
                    dumpingMakePayNet(password,id,encryptKey);
                }
            }
            @Override
            public void exception() {
            }
        };
        task.execute();
    }

    //用户包饺子生成小锅钱包订单（去支付时调用）
    private void dumpingMakeOrderNet() {

        new Dumpling_SinoAsyncTask<Void,Void,Dumpling_DumpingMakeOrderVo>(Dumpling_MakeDumplingActivity.this,false,true){
            @Override
            public Dumpling_DumpingMakeOrderVo before(Void... params) throws Exception {
                return Dumpling_RemoteImpl.getInstance().DumplingMakeOrder(dumpling_make_yuanSum_EditText.getText().toString(),
                        dumpling_make_geNum_EditText.getText().toString(), dumpling_make_messageNum_EditText.getText().toString());
            }

            @Override
            public void after(Dumpling_DumpingMakeOrderVo result) {
                if(result != null){
                    if(result.getCode().toString().equals("100")){
                        orderId = result.getResultList().getDumplingUserPutmoneytid().toString();
                    }else{
                        LogUtils.d("====" + result.getMessage());
                        showToast(result.getMessage());
                    }
                }
            }

            @Override
            public void exception() {

            }
        }.execute();

    }

    //选择支付方式后支付
    private void dumpingMakePayNet(final String password ,final String id, final String encryptKey) {

        new Dumpling_SinoAsyncTask<Void,Void,Dumpling_DumplingPayVo>(Dumpling_MakeDumplingActivity.this,false,true){
            @Override
            public Dumpling_DumplingPayVo before(Void... params) throws Exception {
                if(payStyle == 1) {//余额
                    return Dumpling_RemoteImpl.getInstance().DumplingMakePayEncrption(orderId, password, "包饺子", "包饺子", "1", id, encryptKey);
                }else if(payStyle == 2){//支付宝
                    return Dumpling_RemoteImpl.getInstance().DumplingMakePayEncrption(orderId, "", "包饺子", "包饺子", "2", id, encryptKey);
                }else if(payStyle == 3){//借记卡
                    return Dumpling_RemoteImpl.getInstance().DumplingMakePayEncrption(orderId, "", "包饺子", "包饺子", "3", id, encryptKey);
                }else if(payStyle == 4){//微信
                    return Dumpling_RemoteImpl.getInstance().DumplingMakePayEncrption(orderId, "", "包饺子", "包饺子", "4", id, encryptKey);
                }


                return null;
            }

            @Override
            public void after(Dumpling_DumplingPayVo result) {
                if(result != null){
                    if(payStyle == 1) {
                        if (result.getCode() == 100) {
//                        Toast.makeText(Dumpling_MakeDumplingActivity.this, "余额支付成功", Toast.LENGTH_SHORT).show();
                            dumpingPaySuccessNet();
                        } else {
                            showToast(result.getMessage());
                        }
                    }else if(payStyle == 2){
                        if (result.getCode() == 100) {
//                        Toast.makeText(Dumpling_MakeDumplingActivity.this, "支付宝支付。。。。。。。", Toast.LENGTH_SHORT).show();
                            payVo = result.getResultList();
//                        LogUtils.d("=============" + payVo + "....." + result.getResultList());
                            pay(payVo.getSign());
                        } else {
                            showToast(result.getMessage());
                        }
                    }else if(payStyle == 3){
                        if (result.getCode() == 100) {
//                        Toast.makeText(Dumpling_MakeDumplingActivity.this, "U付支付。。。。。。。", Toast.LENGTH_SHORT).show();
                            payVo =result.getResultList();
                            LogUtils.v("rs.getTrade_no()===="+	result.getResultList().getTrade_no());
                            doUmpay(result.getResultList().getTrade_no());
                        } else {
                            showToast(result.getMessage());
                        }
                    }else if(payStyle == 4){
                        if (result.getCode() == 100) {
//                        Toast.makeText(Dumpling_MakeDumplingActivity.this, "微信支付。。。。。。。", Toast.LENGTH_SHORT).show();

                            payVo = result.getResultList();
                            PayReq req = new PayReq();
                            req.appId			= payVo.getAppid();
                            req.partnerId		= payVo.getPartnerid();
                            req.prepayId		= payVo.getPrepayid();
                            req.nonceStr		= payVo.getNoncestr();
                            req.timeStamp		= payVo.getTimestamp();
                            req.packageValue	="Sign=WXPay";
                            req.sign			= payVo.getSign();
                            LogUtils.v("appId=="+	req.appId+"partnerId=="+payVo.getPartnerid()+"prepayId=="+req.prepayId+"nonceStr=="+req.nonceStr+"timeStamp=="+req.timeStamp+"packageValue=="+req.packageValue+"sign==="+req.sign	);

                            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                            api.sendReq(req);
							/*if(api.sendReq(req)){
								Toast.makeText(W_RechargelActivity.this, "正常调起支付"+api.sendReq(req), Toast.LENGTH_SHORT).show();
							}*/
                            sendWeChatBroadcast(payVo,dumpling_make_yuanSum_EditText.getText().toString(), "Dumpling");//传到微信的回调页面WXPayEntryActivity
                        } else {
                            showToast(result.getMessage());
                        }
                    }
                }
            }

            @Override
            public void exception() {

            }
        }.execute();

    }

    /**
     * 注册接收请求微信的参数对象的广播
     */
//    private void initReciver() {
//        // TODO Auto-generated method stub
//        IntentFilter intentFilter = new IntentFilter();
//        intentFilter.addAction(SinoConstans.KEY_WechatReceiver);
//        weChatReciver = new WXPayEntryActivity.WechatReciver();
//        registerReceiver(weChatReciver, intentFilter);
//    }

    private void sendWeChatBroadcast(Dumpling_DumplingPayVo.DumplingPayListVo rs, String str, String type) {
        Intent intent = new Intent();
        intent.setAction(SinoConstans.KEY_WechatReceiver);
        intent.putExtra("WeChat", rs);
        intent.putExtra("Orderid",orderId);
        intent.putExtra("Type", type);
        sendBroadcast(intent);
    }

    /**
     * call alipay sdk pay. 调用SDK支付
     *  支付宝支付
     */
    public void pay(final String orderInfo) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(Dumpling_MakeDumplingActivity.this);
                // 调用支付接口
                String result = alipay.pay(orderInfo);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                myHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    /**
     * U付支付
     *
     * @param tradeNo 封装数据
     */
    private void doUmpay(String tradeNo) {
        UmpayQuickPay.requestPayWithBind(this, tradeNo, "GoodStudy", "0", null, new UmpPayInfoBean(), REQUESTCODE);
    }

    /**
     * 3.在这里接收并处理U付支付结果
     *
     * @param requestCode
     *            支付请求码
     * @param resultCode
     *            SDK固定返回88888
     * @param data
     *            支付结果和结果描述信息
     * @author niexuyang 2012-8-20
     */

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
     /*   if (requestCode==300&&resultCode==101) {
            if(data!=null){
                String passWord = data.getStringExtra("passWord");
//                Toast.makeText(Dumpling_MakeDumplingActivity.this, "余额支付开始支付", Toast.LENGTH_SHORT).show();
                getDynamicKey(passWord);

            }

        }
        if (requestCode==300&&resultCode==103) {//接收支付密码被锁定后，更改余额支付被锁定状态
            if(data!=null){
                errCount = data.getIntExtra("Num", 0);
                if(errCount>=5){
                    goods_banlance_notice_txt.setVisibility(View.VISIBLE);
                    goods_banlance_notice_txt.setText("锁定");
                    goods_balance_money_txt.setText("账户余额(剩余" + blanceTxt + "元)");
                    pay_fu_bao_img.setVisibility(View.VISIBLE);
                    pay_weChat_img.setVisibility(View.GONE);
                    cash_card_img.setVisibility(View.GONE);
                    pay_wallet_money_img.setVisibility(View.GONE);//余额不足默认选择支付宝
                    payStyle = 2;
                }
            }
        }
*/
        if (requestCode == REQUESTCODE) {
            String umpresultCode = data.getStringExtra("umpResultCode");
            if (UMPAY_SUCCESS.equals(umpresultCode)) {//支付成功
                isRecharge = "1";
                dumpingPaySuccessNet();
            } else if (UMPAY_CANCEL.equals(umpresultCode)) {
                showToast("取消支付");
                isRecharge = "2";
            } else {
                showToast("支付失败");
                isRecharge = "0";
            }
        }
    }

    public class DumplingPayReciver extends BroadcastReceiver {
        public    DumplingPayReciver(){

        }

        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals("com.sinoglobal.dumpling.receiver.passwordNum")){
                int type = intent.getIntExtra("type",-1);
                if(type!=-1){
                    if(type==101){
                        String passWord = intent.getStringExtra("passWord");
//                Toast.makeText(Dumpling_MakeDumplingActivity.this, "余额支付开始支付", Toast.LENGTH_SHORT).show();
                        getDynamicKey(passWord);
                    }else if(type==103){
                        errCount = intent.getIntExtra("Num", 0);
                        if(errCount>=5){
                            goods_banlance_notice_txt.setVisibility(View.VISIBLE);
                            goods_banlance_notice_txt.setText("锁定");
                            goods_balance_money_txt.setText("账户余额(剩余" + blanceTxt + "元)");
                            pay_fu_bao_img.setVisibility(View.VISIBLE);
                            pay_weChat_img.setVisibility(View.GONE);
                            cash_card_img.setVisibility(View.GONE);
                            pay_wallet_money_img.setVisibility(View.GONE);//余额不足默认选择支付宝
                            payStyle = 2;
                        }
                    }
                }
            }

        }
    }
    //2003 用户包饺子后查询支付状态-第三方支付（获取分享链接）
    private void dumpingPaySuccessNet() {

        new Dumpling_SinoAsyncTask<Void,Void,Dumpling_DumplingPaySuccessVo>(Dumpling_MakeDumplingActivity.this,false,true){
            @Override
            public Dumpling_DumplingPaySuccessVo before(Void... params) throws Exception {
                return Dumpling_RemoteImpl.getInstance().DumplingPaySuccess(orderId);
            }

            @Override
            public void after(Dumpling_DumplingPaySuccessVo result) {
                if (result != null) {
                    if (result.getCode() == 100) {
                        if(result.getResultList().getPannikinId().toString() != null) {
                            paySuccessId = result.getResultList().getPannikinId().toString();
                            Intent pay_intent = new Intent();
                            pay_intent.setClass(Dumpling_MakeDumplingActivity.this, Dumpling_DumplingsShareActivity.class);
                            pay_intent.putExtra("paySuccessId", paySuccessId);
                            startActivity(pay_intent);
                            finish();
                        }
                    } else {
                        showToast(result.getMessage());
                    }
                }
            }

            @Override
            public void exception() {

            }
        }.execute();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        unregisterReceiver(weChatReciver);//微信广播取消
        if (myHandler != null) { //退出时清空handler所有队列信息,以防内存泄露
            myHandler.removeCallbacksAndMessages(null);
        }
        unregisterReceiver(dumplingPayReciver);
    }

}
